package com.mjp.learn.multi.juc;

import java.util.Random;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * ReadWriteLock 读写锁
 * 读写锁的读锁是一个共享锁,写锁是一个独享锁
 */
public class Demo04 {

    private static Lock lock = new ReentrantLock();
    private static ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    private static Lock readLock = readWriteLock.readLock();
    private static Lock writeLock = readWriteLock.writeLock();
    private Integer value;

    public Object handleRead(Lock lock) {
        try {
            lock.lock();
            Thread.sleep(1000);
            return value;
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
        return value;
    }

    public void handleWrite(Lock lock, Integer index) {
        try {
            lock.lock();
            Thread.sleep(1000);
            value = index;
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        final Demo04 demo = new Demo04();
        Runnable readRunnable = () -> {
//            demo.handleRead(readLock);
            demo.handleRead(lock);
            System.out.println(Thread.currentThread().getName()+":readThread end!");
        };

        Runnable writeRunnable = () -> {
//            demo.handleWrite(writeLock, new Random().nextInt());
            demo.handleWrite(lock, new Random().nextInt());
            System.out.println(Thread.currentThread().getName()+":writeThread end!");
        };

        for (int i = 0; i < 18; i++) {
            new Thread(readRunnable).start();
        }

        for (int i = 18; i < 20; i++) {
            new Thread(writeRunnable).start();
        }
    }
}
